//引入请求方法
import {request} from '../../request/index.js';
import regeneratorRuntime from '../../lib/runtime/runtime';


// pages/goods_list/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //标题数组
    tabs:[
      {
        id:0,
        value:"综合",
        isActive:true,
      },
      {
        id:1,
        value:"销量",
        isActive:false,
      },
      {
        id:2,
        value:"价格",
        isActive:false,
      }
    ],

    goodList:[],
   
    
  },

   //标题 点击事件，从子组件传递过来的
   handleTabsItemChange(e){
    //console.log(e);
    //获取被点击的标题索引
    const {index} = e.detail;
    //修改源数组
    let {tabs} = this.data;
    tabs.forEach((v,i) => i===index?v.isActive=true:v.isActive=false);
    //赋值到data中
    this.setData({
      tabs
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.QueryParams.cid = options.cid;
    this.getGoodList();

    
  },

  
  //接口调用参数
  QueryParams:{
    query:'',
    cid:'',
    pagenum:1,
    pagesize:10
  },

  totalPages:1,

  //获取商品列表数据
  async getGoodList(){
    const res = await request({url:"https://api-hmugo-web.itheima.net/api/public/v1/goods/search",data:this.QueryParams});
    const total = res.data.message.total;
    this.totalPages = Math.ceil(total/this.QueryParams.pagesize);
    //console.log(this.totalPages);
    this.setData({
      //拼接数组
      goodList:[...this.data.goodList, ...res.data.message.goods],
    })
    //console.log(res);
    // console.log(res.data.message.goods);
    // console.log(this.goodList);
    //关闭下拉刷新的窗口
    wx.stopPullDownRefresh();
  },



  //触底获取数据
  onReachBottom(){
    //判断是否有下一页
    if(this.QueryParams.pagenum >= this.totalPages){
      //没有下一页数据
      wx.showToast({
        title: '没有下一页数据',
      });
        
    }else{
      this.QueryParams.pagenum++;
      this.getGoodList();
    }
  },

  //页面下拉刷新
  onPullDownRefresh(){
    //重置数组
    this.setData({
      goodList:[]
    })
    //重置页码
    this.QueryParams.pagenum = 1;
    //重新发送请求
    this.getGoodList();
  }
})